//index.js
//获取应用实例
const App = getApp();
const navigationBarHeight = (App.statusBarHeight + 44) + 'px'
const topBarHeight = (App.statusBarHeight + 44 + 40) + 'px'
const statusBarHeight = App.statusBarHeight + 'px'
var config = require('../../utils/config');
var net = require('../../utils/net.js');
var util = require('../../utils/util.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;

Page({
  data: {
    topBarHeight,
    navigationBarHeight,
    statusBarHeight,

    focus:false,
    dataArr:[],
    showAddress:false,
    addressArr:[],
    addressName:'上海',
    cityName:'',//编译得到的城市
    isInThisCity:false,
  },
  
  onLoad: function () {
    new App.ToastPannel();
    this.page = 1;
    this.totalPage = 1;
    this.key = -1;
    qqmapsdk = new QQMapWX({
      key: 'IDEBZ-24RER-XFGWY-WSWYS-AZ6NO-IYFU5'
    });

    this.requestAddressList();

    if(App.globalData.isLogin){
      console.log('开始定位');
      this.loadInfo(); 
    }else{
      console.log('等待登录成功');
      App.loginCallback = res => {
        console.log('开始定位');
        // this.requestUserInfo();
        this.loadInfo();
      }
    }  
  },


  //获得当前定位
  loadInfo: function () { 
    wx.getLocation({
       //返回可以用于wx.openLocation的经纬度
      success: res => {
        console.log('定位'+res);
        App.globalData.lat = res.latitude
        App.globalData.lon = res.longitude
        this.latitude = res.latitude//维度
        this.longitude = res.longitude//经度
        this.gotCityName();
      },
      fail: res => {
        wx.showModal({
          title: '警告',
          content: '設定から微信の位置情報サービス利用をオンにしてください',
          success:res=>{
            if(res.confirm){
              wx.openSetting({
                success: res => {
                  this.loadInfo();
                }
              })
            }
          }
        }) 
      }
    }) 
    
  },

  gotCityName:function(){
    console.log('qqmapsdk=',qqmapsdk);
    qqmapsdk.reverseGeocoder({
      location:{
        latitude: this.latitude,
        longitude: this.longitude
      },
      success:res=>{
        var city = res.result.address_component.city+''
        this.setData({
          cityName : city
        })

        console.log('反编译'+city)

        if(this.data.addressArr.length > 0){
          for (var i = 0; i < this.data.addressArr.length; i++) {
            var item = this.data.addressArr[i].name;
            if(city.indexOf(item)>-1){
              this.setData({
                cityName: item,
                addressName: item,
                isInThisCity: true
              }) 
   App.globalData.isInThisCity = true
            }
            break;
          }
          this.requestData();
        }

         

      },
      fail:function(res){
        console.log('失败', res);
      },
      complete:function(res){
        console.log('完成', res);

      }
    });
  },

  requestAddressList:function(){
    var url = config.service.addressUrl;
    var params = {};
    net.doRequest(url, params, 'POST', true, null, res => {
      if (res.code == 0){
        this.setData({
          addressArr:res.data
        })
      }
      if(this.data.cityName.length > 0){
        console.log('定位成功,请求数据');
        if (this.data.addressArr.length > 0) {
          for (var i = 0; i < this.data.addressArr.length; i++) {
            var item = this.data.addressArr[i].name;
            if (city.indexOf(item) > -1) {
              this.setData({
                cityName: item,
                addressName: item,
                isInThisCity: true
              })
              App.globalData.isInThisCity = true
            }
            break;
          }
          this.requestData();
        }

      }


    })

  },

  //请求附近商家
  requestData:function(){
    this.page = 1;
   
 var url = config.service.indexPageUrl;
    var params = {
      cityName: this.data.addressName,
      latitude: this.latitude,
      longitude: this.longitude,
      page: this.page,
      size: 5
    }
    if(!this.data.isInThisCity){
      params = {
        cityName: this.data.addressName,
        page: this.page,
        size: 5
      }
    }

    
    if(this.key != -1){
      params['shopName'] = this.key
    }

    net.doRequest(url, params, 'GET', true, net.Token, res => {
      wx.stopPullDownRefresh();
      wx.hideNavigationBarLoading();
      if (res.code == 0) {
        this.totalPage = res.data.totalPage
        var arr = res.data.items;
        if(arr.length > 0){
          for(var i = 0;i<arr.length;i++){
            var model = arr[i];
            model.isInThisCity = this.data.isInThisCity
            model.shopImg1 = config.service.picUrl + model.shopImg1 
            if (model.distance > 1000){
              model.distance = (model.distance/1000.0).toFixed(1) + 'km'
            }else{
              var num = model.distance;
              model.distance = num.toFixed(1) + 'm';
            }
          }
        }
        this.setData({
          dataArr: arr
        })
      } else {
        this.show(res.message);
      }

    })

  },
  requestMore:function(){
    var url = config.service.indexPageUrl;

    var params = {
      cityName: this.data.addressName,
      latitude: this.latitude,
      longitude: this.longitude,
      page: this.page,
      size: 5
    }
    if (this.data.cityName != this.data.addressName) {
      params = {
        cityName: this.data.addressName,
        page: this.page,
        size: 5
      }
    }

    if (this.key != -1) {
      params['shopName'] = this.key
    }
    net.doRequest(url, params, 'GET', true, net.Token, res => {
      if (res.code == 0) {
        var arr = res.data.items;
        if (arr.length > 0) {
          for (var i = 0; i < arr.length; i++) {
            var model = arr[i];
            model.isInThisCity = this.data.isInThisCity
            model.shopImg1 = config.service.picUrl + model.shopImg1;
            if (model.distance > 1000) {
              model.distance = (model.distance / 1000.0).toFixed(1) + 'km'
            } else {
              var num = model.distance;
              model.distance = num.toFixed(1) + 'm';
            }
          }
        }
        this.setData({
          dataArr: this.data.dataArr.concat(arr)
        })
      } else {
        this.show(res.message);
      }

    })

  },

  addressSelect:function(){
    this.setData({
      showAddress:true
    })

  },

  //cell点击

  itemClick: function(e){
    console.log('点击iTem');
    var index = e.currentTarget.dataset.index;
    var model = this.data.dataArr[index];
    wx.navigateTo({
      url: './indexDetail?shopId='+model.merchantId+'&shopName='+model.shopName
    });

  },

  

  dealFormIds:function(fromId){
    var fromIds = App.globalData.globalFomIds;
    fromIds.push(fromId);
    App.globalData.globalFomIds = fromIds;
  },

  //下拉刷新
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (this.data.searchViewShow == true){
      return;
    }
    wx.showNavigationBarLoading();
    this.totalPage = 1;
    this.page = 1;
    if(this.data.cityName != ' '){
      this.requestData();
      return;
    }
    this.loadInfo();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.searchViewShow == true) {
      return;
    }
    console.log('上啦加载',this.page,this.totalPage);
    if(this.page == this.totalPage){
      this.show('没有更多');
      return;
    }

    this.page ++;
    
    this.requestMore()
  },


  focusClick: function () {
    this.setData({
      focus: true
    })
  },

  searchClick: function (e) {
    console.log('搜索', e.detail.value);
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
    this.key = e.detail.value
    this.requestData()
  },

  serachInput: function (e) {
    console.log('输入', e.detail.value);
    if (e.detail.value.length == 0) {
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
      this.key = -1;
      this.requestData();
    }
  },
  modeTap:function(){
    this.setData({
      showAddress:false
    })
  },

  addressClick:function(e){
    var index = e.currentTarget.dataset.index;
    this.setData({
      showAddress: false,
      addressName:this.data.addressArr[index].name
    })
    if (this.data.cityName != this.data.addressName) {
      this.setData({
        isInThisCity: false
      })
      App.globalData.isInThisCity = false
    } else {
      this.setData({
        isInThisCity: true
      })
      App.globalData.isInThisCity = true
    }

    wx.pageScrollTo({
      scrollTop: 0, //回到顶部
      duration: 500, //过程耗时
    })
    wx.startPullDownRefresh()


  }
   
})
